import numpy as np
import pandas as pd
import os
import csv


def get_np(filename):
    folder_path = "c:/Users/16028/Desktop/mcm/2023c/proj/data"
    file_path = os.path.join(folder_path, filename)
    try:
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found in the specified directory.")
        return None

    column_names = df.columns
    dtype_mapping = {
        "int64": "i8",  # 64位整数
        "float64": "f8",  # 64位浮点数
        "object": "U10",  # 字符串，假设最大长度为50个字符
    }
    dtype = [(name, dtype_mapping[str(df[name].dtype)]) for name in column_names]
    structured_array = np.array([tuple(row) for row in df.to_numpy()], dtype=dtype)
    return structured_array


def get_csv(data, filename):  # 输入numpy数组 存储csv文件中
    folder_path = "c:/Users/16028/Desktop/mcm/2023c/proj/data"
    file_path = os.path.join(folder_path, filename)
    with open(
        file_path,
        mode="w",
        newline="",
        encoding="utf-8",
    ) as file:
        writer = csv.writer(file)
        writer.writerow(data.dtype.names)
        for row in data:
            formatted_row = [f"{x:.4f}" if isinstance(x, float) else x for x in row]
            writer.writerow(formatted_row)


if __name__ == "__main__":
    data = get_np("5.csv")
    get_csv(data, "6.csv")
